<template>
  <div class="activity">
    <h2>促销活动设置</h2>
    <div class="line-container">
      <div class="box">
        <el-input class="el-input" v-model="searchQuery" placeholder="输入活动区域搜索" @keyup.enter="searchUsers"></el-input>
        <el-button class="el-button" @click="searchUsers">
          <img src="../../assets/img/search.png" alt="">
          筛选
        </el-button>
        <el-button @click="showAddDialog" class="el-button process">
          新增活动
        </el-button>
        <el-button class="el-button remove" @click="deleteSelected" :disabled="selectedUsers.length === 0">
          删除
        </el-button>
      </div>
      <el-table :data="currentActivitys" stripe ref="userTable" @selection-change="handleTableSelectionChange">
        <el-table-column type="selection"></el-table-column>
        <el-table-column prop="ActivityName" label="活动名称" width="180"></el-table-column>
        <el-table-column prop="ActivityKind" label="活动区域" ></el-table-column>
        <el-table-column prop="ActivityPicture" label="广告图"  width="150">
          <template slot-scope="scope">
            <img :src="scope.row.ActivityPicture" style="height: 60px;" alt="广告图">
          </template>
        </el-table-column>
        <el-table-column prop="ActivityMain" label="广告内容" width="200"></el-table-column>
        <el-table-column prop="ActivityNumber" label="用户点击量" ></el-table-column>
        <el-table-column prop="ActivitySales" label="活动销售量" ></el-table-column>
        <el-table-column prop="ActivityTime" label="活动开始时间"  width="150">
          <template slot-scope="scope">
            <p>{{ formatTime(scope.row.ActivityTime) }}</p>
          </template>
        </el-table-column>
        <el-table-column label="活动状态" >
          <template slot-scope="scope">
            <el-switch v-model="scope.row.ActivityState" active-color="#13ce66" inactive-color="#ff4949"
              :active-value="true" :inactive-value="false" @change="activityfix(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <p style="color: blue;cursor: pointer;" @click="showDetailDialog(scope.row)">查看详情</p>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
        :page-sizes="[10, 20, 30]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
        :total="totalUsers">
      </el-pagination>
    </div>

    <!-- 查看详情弹窗 -->
    <el-dialog :visible.sync="detailDialogVisible" title="商品详情" width="700px">
      <el-form :model="detail" ref="editForm" label-width="200px">
        <div class="detail-row">
          <div>
            <img :src="detail.ActivityPicture" style="border: 1px solid #ccc;width: 238px; height: 150px;" alt="">
          </div>
          <div>
            <div class="detail-item">
              <h3>{{ detail.ActivityName }}</h3>
            </div>
            <div style="margin-top: 15px;">
              <div class="detail-item">
                <p class="detail-label">活动区域<span>{{ detail.ActivityKind }}</span></p>
              </div>
              <div class="detail-item">
                <p class="detail-label">用户点击量 <span>{{ detail.ActivityNumber }}</span></p>
              </div>
              <div class="detail-item">
                <p class="detail-label">活动销售量 <span>{{ detail.ActivitySales }}</span></p>
              </div>
              <div class="detail-item">
                <p class="detail-label">活动开始时间 <span>{{ formatTime(detail.ActivityTime) }}</span></p>
              </div>
            </div>
            <div class="detail-item">
              <p class="detail-label">广告内容</p>
              <span style="display: block; margin-bottom: 10px;">{{ detail.ActivityMain }}</span>
            </div>
          </div>
        </div>
      </el-form>
      <span style="position: absolute;right: 20px;bottom: 20px;">
        <el-button @click="detailDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="detailDialogVisible = false">确认</el-button>
      </span>
    </el-dialog>

    <!-- 新增活动弹窗 -->
    <el-dialog :visible.sync="addDialogVisible" title="新增活动" width="700px">
      <el-form :model="newActivity" ref="addForm" label-width="200px">
        <div class="detail-row">
          <div>
            <img :src="newActivity.ActivityPicture || 'http://127.0.0.1:3000/picture/1.png'" alt="" style="border: 1px solid #ccc;width: 238px; height: 150px;">
            <form class="uploadForm" enctype="multipart/form-data">
              <input type="file" name="image" placeholder="图片" class="img">
              <button type="button" class="btn" @click="sendImage">完成</button>
            </form>
            <!-- <img :src="newActivity.ActivityPicture" style="border: 1px solid #ccc;width: 238px; height: 150px;" alt=""> -->
          </div>
          <div>
            <div class="detail-item">
              <el-input v-model="newActivity.ActivityName" placeholder="请输入活动名称"></el-input>
            </div>
            <div style="margin-top: 15px;">
              <div class="detail-item1">
                <p class="detail-label1">活动区域</p>
                <el-input v-model="newActivity.ActivityKind" placeholder="请输入活动区域"></el-input>
              </div>
              <div class="detail-item1">
                <p class="detail-label1">活动开始时间</p>
                <el-date-picker v-model="newActivity.ActivityTime" type="datetime" placeholder="请选择活动开始时间"
                  value-format="yyyy-MM-dd"></el-date-picker>
              </div>
            </div>
            <div class="detail-item1">
              <p class="detail-label1">广告内容</p>
              <el-input v-model="newActivity.ActivityMain" placeholder="请输入广告内容"></el-input>
            </div>
          </div>
        </div>
      </el-form>
      <span style="position: absolute;right: 20px;bottom: 20px;">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="activitypost">确认</el-button>
      </span>
    </el-dialog>

    <!-- 删除确认提示框 -->
    <el-dialog :visible.sync="deleteDialogVisible" title="删除活动" width="350px">
      <p>确定要删除（{{ deleteUserNames.join(', ') }}活动）吗？此操作不可恢复</p>
      <span class="dialog-footer" style="margin-top: 20px;display: block;">
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="activitydel">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Message } from 'element-ui';
import jq from "jquery";
import AjaxObj from "../../utils/jqAjaxUrl";
export default {
  data() {
    return {
      activity: [],
      searchQuery: '',
      currentPage: 1,
      pageSize: 10,
      totalUsers: 0,
      detail: {},
      detailDialogVisible: false,
      addDialogVisible: false,
      remark: '',
      selectedCategory: '',
      selectedSeller: '',
      selectedBrowse: '',
      selectedEnquire: '',
      selectedCollect: '',
      selectedTransaction: '',
      batchStatus: '',
      batchRemark: '',
      selectedUsers: [],
      currentIndex: 0,
      inputVisible: false,
      inputValue: '',
      newActivity: {
        ActivityName: '',
        ActivityKind: '',
        ActivityPicture: '',
        ActivityMain: '',
        ActivitySales: '',
        ActivityNumber: '',
        ActivityTime: '',
        ActivityState: false,
      },
      deleteDialogVisible: false,
      deleteUserNames: [],
    };
  },
  mounted() {
    this.goodsactivity()
    document.querySelectorAll('.el-input input, .el-input select').forEach(input => {
      input.addEventListener('focus', () => {
        input.style.outline = 'none';
        input.style.borderColor = '#e2e2e2';
      });
    });
    this.totalUsers = this.activity.length;
  },
  computed: {
    currentActivitys() {
      const searchKey = this.searchQuery.trim().toLowerCase();
      return this.activity.filter(activity =>
        activity.ActivityName.toLowerCase().includes(searchKey) ||
        activity.ActivityKind.toLowerCase().includes(searchKey)
      ).slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
    }
  },
  methods: {
    sendImage() {
      let _this = this;
      const formData = new FormData();
      formData.append('image', document.querySelector('input[name="image"]').files[0]);
      formData.append('ActivityId', _this.newActivity.ActivityId); // 添加 email 参数
      jq.ajax({
        type: "post",
        url: AjaxObj.url + "/ActivityPicture",
        data: formData,
        processData: false,                // jQuery不要去处理发送的数据
        contentType: false,                // jQuery不要去设置Content-Type请求头
        success(res) {
          console.log("发送成功" + res);
          console.log('发送成功')
          if (res.status === 200 && res.data && res.data.ActivityPicture) {
            _this.newActivity.ActivityPicture = res.data.ActivityPicture;
          }
        },
        error(err) {
          console.log("发送失败" + err);
        }
      });
    },
    formatTime(timeStr) {
      if (!timeStr) return '';
      const date = new Date(timeStr);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    },
    //活动查看
    goodsactivity() {
      let _this = this;
      jq.ajax({
        type: "get",
        url: "http://127.0.0.1:3000/goodsactivity",
        data: {
          value: this.add
        },
        success(res) {
          console.log('res', res);
          if (res.data == "") {
            return;
          } else {
            // 处理 ActivityState 数据
            _this.activity = res.data.map(item => {
              return {
                ...item,
                ActivityState: item.ActivityState === '开启' ? true : false
              };
            });
            console.log('_this.activity', _this.activity);
          }
        }
      });
    },
    // 活动删除方法
    activitydel() {
      let _this = this;
      // 遍历选中的用户，依次删除
      this.selectedUsers.forEach(activity => {
        // 错误：this.activity.ActivityId（数组无此属性）
        // activity.ActivityId（当前选中的优惠券对象的属性）
        jq.ajax({
          type: 'delete',
          url: `http://127.0.0.1:3000/activitydel/${activity.ActivityId}`, // 修正此处
          success(res) {
            if (res.status === 200) {
              console.log(`删除优惠卷 ${activity.ActivityName} 成功`);
              // 从 activity 数组中移除已删除的优惠券（根据 ID 过滤）
              _this.activity = _this.activity.filter(item => item.ActivityId !== activity.ActivityId);
            } else {
              Message.error(`删除优惠卷 ${activity.ActivityName} 失败`);
              console.log(`删除优惠券失败，响应状态码:`, res.status);
            }
          },
          error(err) {
            console.error(`删除优惠卷 ${activity.ActivityName} 失败:`, err);
            Message.error(`删除优惠卷 ${activity.ActivityName} 失败`);
          }
        });
      });

      // 清空选中状态
      this.selectedUsers = [];
      this.deleteUserNames = [];
      this.deleteDialogVisible = false;
      this.totalUsers = this.activity.length;
      this.currentPage = 1;
    },
    // 活动状态方法
    activityfix(row) {
      const ActivityState = row.ActivityState ? '开启' : '关闭';
      jq.ajax({
        type: 'put',
        url: `http://127.0.0.1:3000/activityfix`,
        data: {
          ActivityId: row.ActivityId,
          ActivityState: ActivityState
        },
        success(res) {
          if (res.status === 200) {
            Message.success(`更新优惠卷${row.ActivityName} 成功`);
            console.log('更新优惠券成功');
          } else {
            Message.error('更新失败');
            console.log('更新优惠券失败，响应状态码:', res.status);
          }
        },
        error(err) {
          console.error('更新失败:', err);
          Message.error('更新失败');
          // 恢复原来的状态
          row.ActivityState = !row.ActivityState;
        }
      });
    },
    // 活动方法
    activitypost() {
      console.log('进入 activitypost 方法');
      let _this = this;

      const maxNumber = this.activity.length > 0 ?
        Math.max(...this.activity.map(a => parseInt(a.ActivityId.slice(2)), 10)) : 0;
      this.newActivity.ActivityId = `AC${(maxNumber + 1).toString().padStart(5, '0')}`;

      jq.ajax({
        type: 'post',
        url: 'http://127.0.0.1:3000/activitypost',
        data: {
          // 使用value-format后直接获取正确格式字符串，无需额外处理
          ActivityTime: _this.newActivity.ActivityTime,
          ActivityName: _this.newActivity.ActivityName,
          ActivityKind: _this.newActivity.ActivityKind,
          ActivityPicture: _this.newActivity.ActivityPicture,
          ActivityMain: _this.newActivity.ActivityMain,
          ActivityNumber: '0',
          ActivitySales: '0',
          ActivityId: _this.newActivity.ActivityId,
          // 将布尔值转换为字符串
          ActivityState: _this.newActivity.ActivityState ? '开启' : '关闭'
        },
        success(res) {
          if (res.status === 200) {
            _this.addDialogVisible = false;
            _this.activity.push(_this.newActivity);
            _this.totalUsers = _this.activity.length;
            Message.success(`添加活动 ${_this.newActivity.ActivityName} 成功`);
            _this.goodsactivity();
          }
        }
      });
    },

    searchUsers() {
      this.currentPage = 1; // 搜索时重置到第一页
      // 不需要手动过滤，计算属性会自动处理
      // 只需要更新总数量
      this.totalUsers = this.activity.filter(activity =>
        activity.ActivityName.includes(this.searchQuery)
      ).length;
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      // 切换页大小后重置到第一页
      this.currentPage = 1;
      // 更新总数量
      this.totalUsers = this.activity.filter(activity =>
        activity.ActivityName.includes(this.searchQuery)
      ).length;
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
    },
    getStateColor(ActivityState) {
      switch (ActivityState) {
        case '关闭':
          return '#F5F5F5';
        case '开启':
          return '#E8F5E9';
        default:
          return 'transparent';
      }
    },
    getStateTextColor(ActivityState) {
      switch (ActivityState) {
        case '关闭':
          return '#333333';
        case '开启':
          return '#006400';
        default:
          return 'transparent';
      }
    },
    showDetailDialog(row) {
      if (row) {
        this.detail = row;
        this.detailDialogVisible = true;
      } else {
        console.error('传递的行数据row未定义');
      }
    },
    updateGoodsStatus(user, status, remark) {
      return new Promise((resolve) => {
        setTimeout(() => {
          user.ActivityState = status;
          if (status === '不通过') {
            user.processRecord = remark;
          }
          resolve();
        }, 1000);
      });
    },
    confirm() {
      console.log('点击了确认按钮，当前反馈状态：', this.detail.ActivityState);
      this.detailDialogVisible = false;
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick(() => {
        const inputElement = this.$refs.saveTagInput && this.$refs.saveTagInput.$refs.input;
        if (inputElement) {
          inputElement.focus();
        }
      });
    },
    showAddDialog() {
      this.newActivity = {
        ActivityName: '',
        ActivityKind: '',
        ActivityPicture: '',
        ActivityMain: '',
        ActivitySales: '',
        ActivityNumber: '',
        ActivityTime: '',
        ActivityState: false
      };
      this.addDialogVisible = true;
    },
    handleTableSelectionChange(selection) {
      this.selectedUsers = selection;
      this.deleteUserNames = selection.map(activity => activity.ActivityName); // 修正此处);
    },
    deleteSelected() {
      this.deleteDialogVisible = true;
    },
  },
  created() {
    this.totalUsers = this.activity.length;
  }
};
</script>

<style lang="less" scoped>
.activity {
  padding: 70px 20px 20px 230px;
  background-color: #F9FAFB;
  width: 100%;

  h2 {
    display: block;
    visibility: visible;
    margin-left: 10px;
  }

  .line-container {
    box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3);
    border-radius: 10px;
    border: 1px solid #e9e8e8;
    background-color: white;
    position: relative;
    margin: 20px 10px;
    padding: 20px 40px;
    width: 99%;

    .description-ellipsis {
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .box {
      width: 90%;

      select {
        margin-right: 10px;
      }

      .el-input {
        width: 400px;
        height: 40px;
        padding-left: 20px;
        color: #5d5a5a;
        font-size: 16px;
        margin: 10px 0 15px -12px;

        span {
          padding: 10px;
        }

        input {
          padding: 10px 34px;
          border-radius: 5px;
          border: 1px solid #e2e2e2;
          color: #5d5a5a;
        }
      }

      .el-button {
        margin-left: 10px;
        padding: 12px 25px;
        border-radius: 8px;


        img {
          position: relative;
          top: 2px;
          width: 15px;
          height: 15px;
        }
      }

      .remove {
        background-color: #f11f1f;
        color: white;
        position: absolute;
        top: 14px;
        right: 25px;
      }

      .process {
        background-color: #1f3ff1;
        color: white;
        position: absolute;
        top: 15px;
        right: 120px;
      }

      .border {
        border: 1px solid #e2e2e2;
        border-radius: 5px;
        background-color: transparent;
        font-size: 16px;
        padding-left: 20px;

        img {
          position: relative;
          top: 3px;
          right: 2px;
          width: 16px;
          height: 16px;
        }
      }

      .button {
        width: 400px;
        height: 40px;
        margin: 10px;
        border: transparent;
        background-color: #007BFF;
        color: white;
      }

      .color {
        background-color: #1f3ff1;
        color: white;
      }

    }

    h3 {
      display: block;
      padding: 30px 0 20px 20px;
    }
  }

  .pop {
    display: inline-block;
    vertical-align: top;
    margin-left: 10px;

    p {
      font-size: 17px;
    }
  }

  .detail-row {
    display: flex;
    justify-content: space-around;
    margin-bottom: 30px;
    width: 100%;
  }

  .detail-main {
    width: 90%;
  }

  .detail-item {
    flex: 1;
    margin-right: 10px;
  }

  .detail-item1 {
    flex: 1;
    margin-right: 10px;
    display: flex;
    justify-content: space-between;
  }


  .detail-label {
    display: block;
    color: rgb(160, 160, 160);
    margin-bottom: 5px;
    font-weight: normal;

    span {
      color: #5d5a5a;
      margin: 0 10px;
    }
  }

  .detail-label1 {
    width: 100px;
    display: block;
    color: rgb(160, 160, 160);
    margin-bottom: 5px;
    font-weight: normal;

    span {
      color: #5d5a5a;
      margin: 0 10px;
    }
  }

  .close-button {
    background-color: #f4f4f4;
    color: #666;
    border: 1px solid #ccc;
  }

  .send-button {
    background-color: #409eff;
    color: white;
    border: none;
  }

  .confirm-button {
    background-color: #27c24c;
    color: white;
    border: none;
  }

  .stats-container {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    margin: 20px 10px;
  }

  .stat-item {
    width: calc(50% - 20px);
    margin-bottom: 20px;
    box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3);
    border-radius: 10px;
    border: 1px solid #e9e8e8;
    background-color: white;
    border-radius: 5px;
    padding: 20px;
  }

  .stat-item-1 {
    width: calc(25% - 20px);
    margin-bottom: 20px;
    box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3);
    border-radius: 10px;
    border: 1px solid #e9e8e8;
    background-color: white;
    border-radius: 5px;
    padding: 20px;
  }

  .stat-value {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 10px;
  }

  .stat-change {
    color: green;
  }

  .increase {
    color: green;
  }

  .decrease {
    color: red;
  }

  .stat-tip {
    color: rgb(255, 115, 0);
  }
}
</style>